<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class BaseModel extends Model
{


//    use \App\Traits\OperationLog;

    public static function boot()
    {
        parent::boot();

//        self::deleteLog();

        /*parent::boot();
        static::deleted(function($model){
            $path = request()->path();
            if ($path == 'admin/_handle_action_') {// 列表：单个删除
                $path = request()->header('referer');
                $path = strstr($path,'admin');
            }
            $pageName = Menu::getPageName($path);

//            \Log::info($pageName);
//            throw new \Exception('无法删除');

            // 操作日志
            dispatch(
                new \App\Jobs\OperationLog(
                    $pageName['module'],
                    $pageName['page'],
                    auth()->user()->id,
                    $path,
                    'DELETE',
                    'ID =>'.$model->id,  //删除的描述
                    $model->toArray()
                )
            );

        });*/
    }

    protected function updateBatch($multipleData = [])
    {
        $tableColumn = Schema::getColumnListing($this->getTable());
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            $tableName = $this->getTable(); // 表名
            $firstRow = current($multipleData);
            $dataColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($dataColumn);
            unset($dataColumn[0]);
            // 拼接sql语句
            $updateColumn = array_intersect($dataColumn, $tableColumn);
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets  = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return \DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            echo $e->getMessage();
            return false;
        }
    }

}
